package cn.com.ccxe.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ccxe.manage.service.CurrUserInfo;
import com.ccxe.manage.service.MenuHandler;

public class SessionFilter implements Filter {
	private static final long 		serialVersionUID = 1L;
	private static final Logger 	logger = LoggerFactory.getLogger(SessionFilter.class);

	/**
	 * 初始化过滤器配置
	 */
	public void init(FilterConfig config) throws ServletException {
	}

	/**
	 * 运行过滤器
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest servletRequest = (HttpServletRequest) request;
		HttpServletResponse servletResponse = (HttpServletResponse) response;
		HttpSession session = servletRequest.getSession();
		session.setMaxInactiveInterval(60 * 10);// 10秒过期
		CurrUserInfo cui = (CurrUserInfo) session.getAttribute("currUser");
		MenuHandler mh = new MenuHandler();

		String url = servletRequest.getRequestURI();
		
		url = url.substring(url.lastIndexOf("/"), url.length());
		if(url.indexOf("/") > 0) {
			url = url.substring(0,url.indexOf("?")-1);
		}
		if (!("".equals(url))) {
			try {
				// 排除后台不作权限控制的页面名
				String exclude = "/index.jsp,/js,/login,/login.jsp,base.jsp,error.jsp,menubase.jsp,message.jsp"
						+ "redirect.jsp,login.jsp,forward.jsp,/stlye.css,";

				// 当获取url文件名与不做权限验证的页面不同时
				if (exclude.indexOf(url.toString()) == -1) {
					// 获取网站访问根目录
					// String accessPath = servletRequest.getContextPath();
					// 当用户名,和密码不存在或者为空字符串时
					if (cui == null || cui.getCusId().trim().length() == 0) {
						// RequestDispatcher dispatcher = request
						// .getRequestDispatcher("/servlet/login/loginout");
						// 将这个请求url放在session中以便登录成功后能自动跳转到该url
						// dispatcher.forward(servletRequest, servletResponse);

						java.io.PrintWriter out = servletResponse.getWriter();
						out
								.println("<script type='text/javascript'>top.window.location='"
										+ servletRequest.getContextPath()
										+ "/login.jsp';</script>");
						 session.setAttribute("requrl", url);
						return;
					} else {
						if (cui != null) {
							boolean isAccess = false;
							try {
								isAccess = mh.canUse(cui.getUserId(), url);
							}finally {
								if (!isAccess) {
									logger.debug("您对 {}  没有访问权限 ，请联系管理员！", url);
									request.setAttribute("message", "您没有访问权限 ，请联系管理员！");
									request.getRequestDispatcher("/common/success.jsp").forward(request,
									response);
									return;
								}
							}
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		session.setAttribute("currUser", cui);
		filterChain.doFilter(request, response);
	}

	/**
	 * 销毁
	 */
	public void destroy() {
	}
}
